package cn.web.management.web.servlet.account;

import cn.web.management.domain.UserInform;
import cn.web.management.domain.UserState;
import cn.web.management.service.inface.LoginVerify;
import cn.web.management.service.impl.LoginVerifyImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "newUserServlet", value = "/newUserServlet")
public class newUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    /**
     * @description: 用户登录或者注册，为其添加在线状态等新，设定其初始头像等信息，以便登录后的界面获取头像信息
     * 之后根据登录或注册的身份，重定向到用户/管理员界面
     * @paramName: [req, resp]
     * @paramType: [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @returnType: void
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String identity = req.getParameter("identity");
        String um = req.getParameter("user");
        String employno = "";

        UserState userState = new UserState();
        userState.setState("online");
        userState.setUsername(username);
        userState.setIdentity(identity);
        String user = (String) req.getAttribute("user");

        LoginVerify loginVerify = new LoginVerifyImpl();
        List<UserInform> list = loginVerify.findUserNamePassword();


        UserInform u;
        for (int i = 0; i < list.size(); i++) {
            u = list.get(i);
            if(username.equals(u.getUsername())){
                employno = u.getEmployno();
                userState.setUserPortrait(u.getUserPortrait());
                break;
            }
        }

        HttpSession session = req.getSession();
        session.setAttribute("userState",userState);
        session.setAttribute("employno",employno);
        session.setMaxInactiveInterval(1000*60*20);
        if(identity==null)
            resp.sendRedirect("/html/userInterface.html");
        else if(identity.equals("admin"))
            resp.sendRedirect("html/adminInterface.html");
        else
            resp.sendRedirect("/html/userInterface.html");
    }
}
